<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								供应商管理
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="供应商分级" prop="supplierClassification">
									<el-select @clear="selectClear('supplierClassification')"
										v-model="formData.supplierClassification"
										@change="(value:any)=>selectChange(value,'supplierClassification')" multiple
										ref="supplierClassification" clearable>
										<el-option v-for="(item, key) in supplierClassificationOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<el-tag style="border: 0;" :color="item?.color" round effect="dark">
												{{ item?.label }}
											</el-tag>
											<!--  -->
										</el-option>
										<!--  -->
										<template #tag>
											<el-tag style="border: 0;"
												v-show="supplierClassificationOption[supplierClassificationIndex]?.value"
												:color="supplierClassificationOption[supplierClassificationIndex]?.color"
												round effect="dark">
												{{ supplierClassificationOption[supplierClassificationIndex]?.label }}
											</el-tag>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="合作状态" prop="collaborationStatus">
									<el-select @clear="selectClear('collaborationStatus')"
										v-model="formData.collaborationStatus"
										@change="(value:any)=>selectChange(value,'collaborationStatus')" multiple
										ref="collaborationStatus" clearable>
										<el-option v-for="(item, key) in collaborationStatusOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<el-tag style="border: 0;" :color="item?.color" round effect="dark">
												{{ item?.label }}
											</el-tag>
											<!--  -->
										</el-option>
										<!--  -->
										<template #tag>
											<el-tag style="border: 0;"
												v-show="collaborationStatusOption[collaborationStatusIndex]?.value"
												:color="collaborationStatusOption[collaborationStatusIndex]?.color"
												round effect="dark">
												{{ collaborationStatusOption[collaborationStatusIndex]?.label }}
											</el-tag>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="供应商简称" prop="supplierShortName">
							<el-input placeholder="请填写" v-model="formData.supplierShortName" type="text" clearable></el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="联系人" class="form-item-bg" prop="contactPerson">
									<el-input placeholder="请填写" v-model="formData.contactPerson" type="text" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="手机号" class="form-item-bg" prop="phoneNumber">
									<el-input placeholder="请填写" v-model="formData.phoneNumber" type="text" clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>结算信息</div>
						</div>
						<el-row :gutter="20">
							<el-col :span="billingMethodIndex===1?6:24">
								<el-form-item label="结算方式" prop="billingMethodId">
									<el-input class="my" readonly type="text" v-model="formData.billingMethodId"
										clearable>
										<template #prefix>
											<div>
												<el-check-tag
													:style="`color: ${billingMethodIndex===key?'#fff':''};${billingMethodIndex===key?`background: ${item.bg}`:''}`"
													v-for="(item,key) in billingMethodTags" :key="key"
													:checked="billingMethodIndex===key"
													@change="tagChange(key,'billingMethodId')">{{item.text}}</el-check-tag>
											</div>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col v-show="billingMethodIndex===1" :span="6">
								<el-form-item label="账单周期" prop="billingCycle">
									<el-input v-model="formData.billingCycle" type="text" clearable>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col v-show="billingMethodIndex===1" :span="6">
								<el-form-item label="上次对账日" prop="lastReconciliationDate">
									<el-date-picker style="width: 100%;" v-model="formData.lastReconciliationDate"
										type="date" />
								</el-form-item>
							</el-col>
							<el-col v-show="billingMethodIndex===1" :span="6">
								<el-form-item label="下次对账日" prop="nextReconciliationDate">
									<el-date-picker style="width: 100%;" disabled v-model="formData.nextReconciliationDate"
										type="date" clearable/>
								</el-form-item>
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>账款信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="6">
								<el-form-item label="采购总额" prop="totalPurchaseAmount">
									<el-input v-model="formData.totalPurchaseAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="应付总额" prop="totalPayableAmount">
									<el-input v-model="formData.totalPayableAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="已对账总额" prop="totalReconciledAmount">
									<el-input v-model="formData.totalReconciledAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="待对账总额" prop="totalUnreconciledAmount">
									<el-input v-model="formData.totalUnreconciledAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="8">
								<el-form-item label="延期率" prop="delayRate">
									<el-input v-model="formData.delayRate" type="text" placeholder="自动计算结果"
										disabled clearable :parser="(value)=>value ? value+'%' : ''"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="待付款金额" prop="unpaidAmount">
									<el-input v-model="formData.unpaidAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="已付款金额" prop="paidAmount">
									<el-input v-model="formData.paidAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="待回票金额" prop="unpaidInvoiceAmount">
									<el-input v-model="formData.unpaidInvoiceAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="已回票金额" prop="paidInvoiceAmount">
									<el-input v-model="formData.paidInvoiceAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { getShipments } from '../../../api/shipmentAPI';
	import { ElMessage, FormInstance } from 'element-plus';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		supplierClassificationId: null,//供应商分级
		supplierClassification: [],
		collaborationStatusId: null,//合作状态
		collaborationStatus: [],
		supplierShortName: null,//供应商简称
		contactPerson: null,//联系人
		phoneNumber: null,//手机号
		billingMethodId: null,//结算方式
		billingCycle: null,//账单周期
		lastReconciliationDate: null,//上次对账日
		nextReconciliationDate: null,//下次对账日
		totalPurchaseAmount: null,//采购总额
		totalPayableAmount: null,//应付总额
		totalReconciledAmount: null,//已对账总额
		totalUnreconciledAmount: null,//待对账总额
		delayRate: null,//延期率
		unpaidAmount:null,//待付款金额
		paidAmount:null,//已付款金额
		unpaidInvoiceAmount:null,//待回票金额
		paidInvoiceAmount:null,//已回票金额
	});
	//验证
	const rules = reactive({
		supplierClassification: [{ required: true, message: '不能为空', trigger: 'blur' }],//供应商分级
		collaborationStatus: [{ required: true, message: '不能为空', trigger: 'blur' }],//合作状态
		supplierShortName: [{ required: true, message: '不能为空', trigger: 'blur' }],//供应商简称
		contactPerson: [{ required: true, message: '不能为空', trigger: 'blur' }],//联系人
		phoneNumber: [{ required: true, message: '不能为空', trigger: 'blur' }],//手机号
		billingMethodId: [{ required: true, message: '不能为空', trigger: 'blur' }],//结算方式
		totalPurchaseAmount: [],//采购总额
		totalPayableAmount: [],//应付总额
		totalReconciledAmount: [],//已对账总额
		totalUnreconciledAmount: [],//待对账总额
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
		list: []
	});
	//供应商分级
	const supplierClassificationOption = ref([]);
	const supplierClassificationIndex = ref(-1);
	const supplierClassification = ref(null);
	//合作状态
	const collaborationStatusOption = ref([]);
	const collaborationStatusIndex = ref(-1);
	const collaborationStatus = ref(null);
	//结算方式
	const billingMethodTags = ref([]);
	const billingMethodIndex = ref(-1);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getsupplierClassificationList();
				getcollaborationStatusList();
				getbillingMethodList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			return true;
		}
		//
		const result = await request({
			url: '/demand/selectSupplierById',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'supplierClassification', //哪一个下拉框，根据ref
			option: supplierClassificationOption, //下拉列表选项
			indexVar: supplierClassificationIndex, //当前选中项
			idVar: 'supplierClassificationId', //当前id值
			blurRef: supplierClassification, //ref
		}, {
			type: 'collaborationStatus', //哪一个下拉框，根据ref
			option: collaborationStatusOption, //下拉列表选项
			indexVar: collaborationStatusIndex, //当前选中项
			idVar: 'collaborationStatusId', //当前id值
			blurRef: collaborationStatus, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		if (type === 'billingMethodId') {
			if (billingMethodIndex.value === index) {
				formData.value[type] = 0;
				billingMethodIndex.value = -1;
				return;
			}
			billingMethodIndex.value = index;
			formData.value[type] = billingMethodTags.value[index].value;
		}
	}
	//获取供应商分级
	const getsupplierClassificationList = async () => {
		const data = await getShipments('supplier_classification', 'option');
		console.log('getsupplierClassificationList --->', data);
		//
		supplierClassificationOption.value.splice(0, supplierClassificationOption.value.length);

		data.forEach((item : any, key : number) => {
			supplierClassificationOption.value.push(item);
			//
			if (formData.value.supplierClassificationId === item.value) {
				formData.value.supplierClassification = [item.value];
				supplierClassificationIndex.value = key;
			}
		});
	}
	//获取合作状态
	const getcollaborationStatusList = async () => {
		const data = await getShipments('collaboration_status', 'option');
		console.log('getcollaborationStatusList --->', data);
		//
		collaborationStatusOption.value.splice(0, collaborationStatusOption.value.length);
		data.forEach((item : any, key : number) => {
			collaborationStatusOption.value.push(item);
			//
			if (formData.value.collaborationStatusId === item.value) {
				formData.value.collaborationStatus = [item.value];
				collaborationStatusIndex.value = key;
			}
		});
		//
	}
	//获取结算方式
	const getbillingMethodList = async () => {
		const data = await getShipments('billing_method', 'tag');
		console.log('getcollaborationStatusList --->', data);
		//
		billingMethodTags.value.splice(0, billingMethodTags.value.length);
		data.forEach((item : any, key : number) => {
			billingMethodTags.value.push(item);
			//
			if (formData.value.billingMethodId === item.value) {
				billingMethodIndex.value = key;
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.collaborationStatus;
				delete data.supplierClassification;
				let type = '';
				if (!route.query.id) {
					type = '/addProcuredSupplier';
				} else {
					type = '/updateSupplierById';
				}
				//
				const result = await request({
					url: '/demand' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//

				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>